import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Modal, Form, Input, Select, InputNumber, Upload, message, Row, Col, Tag, Image, Typography, Tooltip, Badge, Dropdown, Menu as AntMenu, Switch, DatePicker, Statistic } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, UploadOutlined, SearchOutlined, FilterOutlined, MoreOutlined, ShoppingOutlined, DollarOutlined, StarOutlined, FireOutlined, ReloadOutlined, ExportOutlined, ImportOutlined, DownloadOutlined } from '@ant-design/icons';
import BaseTable from '../shared/table/BaseTable';
import dayjs from 'dayjs';
import { menuAPI, authAPI } from '../utils/api';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const ImprovedMenuPage = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(!!localStorage.getItem('admin_token'));
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [loginLoading, setLoginLoading] = useState(false);
  
  const handleLogin = async () => {
    setLoginLoading(true);
    try {
      console.log('登录表单数据:', loginForm);
      const response = await authAPI.login(loginForm);
      console.log('登录响应:', response);
      
      if (response.data && response.data.data && response.data.data.token) {
        const { token } = response.data.data;
        localStorage.setItem('admin_token', token);
        message.success('登录成功');
        setIsLoggedIn(true);
      } else {
        message.error(response.data?.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error(error.response?.data?.message || '登录时发生错误');
    } finally {
      setLoginLoading(false);
    }
  };
  
  const handleLogout = () => {
    localStorage.removeItem('admin_token');
    setIsLoggedIn(false);
    message.success('已退出登录');
  };
  
  const [menuItems, setMenuItems] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 将fetchMenuItems提取为独立函数，便于重用
  const fetchMenuItems = async () => {
    try {
      setLoading(true);
      const response = await menuAPI.getMenuItems();
      console.log('菜单API响应:', response);
      
      if (response.data && response.data.success && response.data.data && response.data.data.items) {
        // 确保每个菜单项的所有属性都是可渲染的
        const safeMenuItems = response.data.data.items.map(item => ({
          ...item,
          // 确保所有可能是对象的字段都被转换为字符串
          id: item.id ? String(item.id) : '',
          name: item.name ? String(item.name) : '',
          description: item.description ? String(item.description) : '',
          category: item.category ? String(item.category) : '',
          price: typeof item.price === 'number' ? item.price : 0,
          originalPrice: typeof item.originalPrice === 'number' ? item.originalPrice : 0,
          stock: typeof item.stock === 'number' ? item.stock : 0,
          sales: typeof item.sales === 'number' ? item.sales : 0,
          status: item.status ? String(item.status) : 'unavailable',
          isHot: !!item.isHot,
          isNew: !!item.isNew,
          image: item.image ? String(item.image) : '',
          // 映射main_ingredients字段以匹配表格列定义
          main_ingredients: item.main_ingredients || item.ingredients || []
        }));
        
        setMenuItems(safeMenuItems);
        console.log('菜单数据已更新:', safeMenuItems);
        console.log('第一个菜品的main_ingredients:', safeMenuItems[0]?.main_ingredients);
      } else {
        console.warn('菜单API响应格式异常:', response);
        setMenuItems([]);
      }
    } catch (error) {
      console.error('获取菜单数据失败:', error);
      message.error('获取菜单数据失败');
      setMenuItems([]);
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    const fetchMenuItemsWrapper = async () => {
      try {
        setLoading(true);
        const response = await menuAPI.getMenuItems();
        console.log('菜单API响应:', response);
        
        if (response.data && response.data.success && response.data.data && response.data.data.items) {
          // 确保每个菜单项的所有属性都是可渲染的
          const safeMenuItems = response.data.data.items.map(item => ({
            ...item,
            // 确保所有可能是对象的字段都被转换为字符串
            id: item.id ? String(item.id) : '',
            name: item.name ? String(item.name) : '',
            description: item.description ? String(item.description) : '',
            category: item.category ? String(item.category) : '',
            price: typeof item.price === 'number' ? item.price : 0,
            originalPrice: typeof item.originalPrice === 'number' ? item.originalPrice : 0,
            stock: typeof item.stock === 'number' ? item.stock : 0,
            sales: typeof item.sales === 'number' ? item.sales : 0,
            status: item.status ? String(item.status) : 'unavailable',
            isHot: !!item.isHot,
            isNew: !!item.isNew,
            image: item.image ? String(item.image) : '',
            // 映射main_ingredients字段以匹配表格列定义
            main_ingredients: item.main_ingredients || item.ingredients || []
          }));
          
          setMenuItems(safeMenuItems);
          console.log('菜单数据已更新:', safeMenuItems);
          console.log('第一个菜品的main_ingredients:', safeMenuItems[0]?.main_ingredients);
        } else {
          console.warn('菜单API响应格式异常:', response);
          setMenuItems([]);
        }
      } catch (error) {
        console.error('获取菜单数据失败:', error);
        message.error('获取菜单数据失败');
        setMenuItems([]);
      } finally {
        setLoading(false);
      }
    };

    const fetchCategories = async () => {
      try {
        const response = await fetch('/api/admin/import/categories', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          const categoryData = data.data || [];
          // 转换为前端需要的格式
          const formattedCategories = categoryData.map(cat => ({
            value: cat.name,
            label: cat.name,
            color: cat.color || '#1890ff'
          }));
          setCategories(formattedCategories);
        } else {
          console.error('获取分类数据失败');
        }
      } catch (error) {
        console.error('获取分类数据失败:', error);
      }
    };
    
    if (isLoggedIn) {
      fetchMenuItemsWrapper();
      fetchCategories();
    }
  }, [isLoggedIn]);

  const [categories, setCategories] = useState([]);

  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [templateLoading, setTemplateLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [dateRange, setDateRange] = useState(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [stats, setStats] = useState({
    totalItems: 0,
    availableItems: 0,
    hotItems: 0,
    totalSales: 0
  });

  // 计算过滤后的数据
  const filteredData = menuItems.filter(item => {
    // 搜索文本过滤
    if (searchText && !String(item.name).toLowerCase().includes(searchText.toLowerCase()) && 
        !String(item.description).toLowerCase().includes(searchText.toLowerCase()) ) {
      return false;
    }
    
    // 分类过滤
    if (categoryFilter !== 'all' && item.category !== categoryFilter) {
      return false;
    }
    
    // 状态过滤
    if (statusFilter !== 'all' && item.status !== statusFilter) {
      return false;
    }
    
    // 日期范围过滤
    if (dateRange && dateRange.length === 2) {
      const itemDate = dayjs(item.createTime);
      if (itemDate.isBefore(dateRange[0]) || itemDate.isAfter(dateRange[1])) {
        return false;
      }
    }
    
    return true;
  });

  useEffect(() => {
    calculateStats();
  }, [menuItems]);

  const calculateStats = () => {
    const totalItems = menuItems.length;
    const availableItems = menuItems.filter(item => item.status === 'available').length;
    const hotItems = menuItems.filter(item => item.isHot).length;
    const totalSales = menuItems.reduce((sum, item) => sum + (typeof item.sales === 'number' ? item.sales : 0), 0);

    setStats({
      totalItems,
      availableItems,
      hotItems,
      totalSales
    });
  };

  const getStatusColor = (status) => {
    const colors = {
      available: 'success',
      unavailable: 'error',
      hidden: 'warning'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      available: '可售',
      unavailable: '缺货',
      hidden: '隐藏'
    };
    return texts[status] || String(status);
  };

  // 添加状态更新函数
  const handleStatusChange = async (itemId, newStatus) => {
    try {
      // 调用API更新状态到后台
      const statusData = { is_available: newStatus === 'available' };
      const response = await menuAPI.updateAvailability(itemId, statusData);
      
      if (response.data && response.data.success) {
        message.success('状态更新成功');
        // 重新获取最新数据
        await fetchMenuItems();
      } else {
        message.error(response.data?.message || '状态更新失败');
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
    }
  };

  const getCategoryColor = (category) => {
    const categoryObj = categories.find(cat => cat.value === category);
    return categoryObj ? categoryObj.color : '#666';
  };

  const handleEdit = (item) => {
    setEditingItem(item);
    // 设置预览图片，如果是相对路径则添加服务器基础地址
    if (item.image_url) {
      const fullImageUrl = item.image_url.startsWith('/') ? `http://localhost:3001${item.image_url}` : item.image_url;
      setPreviewImage(fullImageUrl);
    } else {
      setPreviewImage('');
    }
    form.setFieldsValue({
      name: item.name,
      name_en: item.name_en,
      description: item.description,
      description_en: item.description_en,
      category: item.category?.value || item.category,
      price: item.price,
      originalPrice: item.originalPrice,
      main_ingredients: Array.isArray(item.main_ingredients) ? item.main_ingredients.join(', ') : item.main_ingredients,
      status: item.status,
      isHot: item.isHot,
      isNew: item.isNew,
      stock: item.stock,
      tags: item.tags || [],
      options: item.options || [],
      is_available: item.is_available
    });
    setModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个菜品吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setMenuItems(menuItems.filter(item => item.id !== id));
        message.success('删除成功');
      }
    });
  };

  const handleDownloadTemplate = async () => {
    try {
      setTemplateLoading(true);
      message.loading('正在准备下载模板...', 0);
      
      console.log('下载模板按钮已点击');
      
      const response = await menuAPI.downloadTemplate();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单导入模板_${dayjs().format('YYYY-MM-DD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('模板下载成功');
    } catch (error) {
      console.error('下载模板失败:', error);
      message.destroy();
      message.error('下载模板失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setTemplateLoading(false);
    }
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      message.loading('正在准备导出...', 0);
      
      console.log('导出按钮已点击');
      
      // 使用V2三表结构API导出
      const response = await menuAPI.exportMenu();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单数据_${dayjs().format('YYYY-MM-DD')}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.destroy();
      message.error('导出失败: ' + (error.response?.data?.message || error.message));
    } finally {
      setExportLoading(false);
    }
  };

  // 添加导入调试日志功能
  const [importLogs, setImportLogs] = useState([]);
  
  // 检查URL参数是否启用导入调试
  const isImportDebugEnabled = () => {
    if (typeof window === 'undefined') return false;
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('importDebug') === '1';
  };
  
  // 添加导入日志
  const addImportLog = (type, message, data = null) => {
    if (!isImportDebugEnabled()) return;
    
    const logEntry = {
      timestamp: new Date().toISOString(),
      type,
      message,
      data
    };
    
    console.log(`[menu-import-debug] ${type}:`, message, data);
    setImportLogs(prev => [...prev, logEntry]);
    
    // 同时保存到window对象，方便导出
    if (typeof window !== 'undefined') {
      window.__menuImportLogs = window.__menuImportLogs || [];
      window.__menuImportLogs.push(logEntry);
    }
  };
  
  // 导出日志功能
  const exportImportLogs = () => {
    if (!window.__menuImportLogs || window.__menuImportLogs.length === 0) {
      message.info('没有可导出的导入日志');
      return;
    }
    
    const logText = JSON.stringify(window.__menuImportLogs, null, 2);
    const blob = new Blob([logText], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `menu_import_logs_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success('导入日志已导出');
  };

  // V2三表结构导入功能
  const handleImport = () => {
    console.log('导入按钮已点击');
    addImportLog('click', '导入按钮已点击');
    message.info({ key: 'menu-import-select', content: '请选择要导入的Excel文件' });
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    input.style.display = 'none';
    document.body.appendChild(input);
    
    const cleanup = () => {
      try { document.body.removeChild(input); } catch {}
    };
  
    input.addEventListener('change', async (e) => {
      const file = e.target.files && e.target.files[0];
      if (!file) { cleanup(); return; }
      
      console.log('[IMPORT] start', Date.now());
      
      try {
        setImportLoading(true);
        
        console.log('开始导入V2三表结构Excel');
        addImportLog('upload_start', '开始上传文件', { filename: file.name, size: file.size });
        
        // 使用V2三表结构API导入
        const hide = message.loading('正在上传并触发验证...', 0);
        try {
          const validateResponse = await menuAPI.validateMenu(file);
          addImportLog('validate_response', '收到验证响应', validateResponse.data);
          
          const { job_id, validation_result } = validateResponse.data || {};
          if (!job_id) {
            hide();
            message.error('验证失败：未返回任务ID');
            addImportLog('error', '验证失败：未返回任务ID');
            return;
          }
  
          // 若立即返回验证失败，则直接下载错误报告
          if (validation_result && validation_result.success === false) {
            hide();
            message.error('验证失败：' + (validation_result.message || '格式错误'));
            addImportLog('validation_failed', '验证立即失败', validation_result);
            
            try {
              const errorResponse = await menuAPI.downloadErrors(job_id);
              const url = window.URL.createObjectURL(new Blob([errorResponse.data]));
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `导入错误报告_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            } catch (errorDownloadError) {
              console.error('下载错误报告失败:', errorDownloadError);
              addImportLog('error_download_failed', '下载错误报告失败', errorDownloadError);
            }
            return;
          }
          
          // 轮询任务状态
          hide();
          message.loading({ content: '正在验证数据...', key: 'menu-import-validate', duration: 0 });
          
          const start = Date.now();
          const timeoutMs = 60000; // 60秒超时
          const pollIntervalMs = 1500; // 1.5秒轮询一次
          
          let job = { status: 'uploaded' };
          let attempts = 0;
          const maxAttempts = 40; // 最多轮询40次
          
          while (job.status === 'uploaded' || job.status === 'validating') {
            if (attempts >= maxAttempts) {
              addImportLog('polling_max_attempts', '达到最大轮询次数', { attempts });
              break;
            }
            
            // 处理超时情况
            if (Date.now() - start >= timeoutMs) {
              addImportLog('timeout', '校验超时', { elapsed_ms: Date.now() - start });
              message.destroy('menu-import-validate');
              Modal.warning({
                title: '校验超时',
                content: '校验操作超时，请在导入中心查看结果',
                onOk: () => {}
              });
              return;
            }
            
            // 等待一段时间再轮询
            await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
            
            try {
              console.log(`轮询任务状态 (${attempts + 1}/${maxAttempts})...`);
              addImportLog('polling', `轮询任务状态 (${attempts + 1}/${maxAttempts})`, { job_id });
              
              const statusResponse = await menuAPI.getJobStatus(job_id);
              job = statusResponse.data;
              addImportLog('polling_response', '轮询响应', job);
              
              attempts++;
            } catch (pollError) {
              console.error('轮询任务状态失败:', pollError);
              addImportLog('polling_error', '轮询任务状态失败', pollError);
              message.destroy('menu-import-validate');
              message.error('获取任务状态失败，请稍后重试');
              return;
            }
          }
          
          message.destroy('menu-import-validate');
          
          // 处理验证完成的情况
          if (job.status === 'validated') {
            console.log('验证成功，准备提交导入');
            addImportLog('validation_success', '验证成功，准备提交导入', job);
            
            try {
              // 显示确认对话框
              Modal.confirm({
                title: '导入确认',
                content: (
                  <div>
                    <p>验证成功，是否确认导入数据？</p>
                    <p>此操作将更新菜单数据，无法撤销。</p>
                  </div>
                ),
                onOk: async () => {
                  const loadingKey = 'menu-import-commit';
                  try {
                    message.loading({ content: '正在导入数据...', key: loadingKey, duration: 0 });
                    console.log('提交导入，任务ID:', job.job_id || job_id);
                    addImportLog('commit_start', '开始提交导入', { job_id: job.job_id || job_id });
                    
                    // 确保使用正确的任务ID
                    const taskId = job.job_id || job_id;
                    if (!taskId) {
                      message.error({ key: 'menu-import-commit-error', content: '提交失败: 无效的任务ID' });
                      addImportLog('error', '提交失败: 无效的任务ID');
                      return;
                    }
                    
                    try {
                      // 使用menuAPI.commitImport函数提交导入
                      const commitResponse = await menuAPI.commitImport(taskId);
                      
                      addImportLog('commit_response', '提交导入响应', commitResponse.data);
                      
                      if (commitResponse.data && commitResponse.data.success) {
                        message.success({ key: loadingKey, content: '导入成功' });
                        addImportLog('commit_success', '导入成功', commitResponse.data);
                        
                        // 刷新页面或重新加载数据
                        setTimeout(() => {
                          window.location.reload();
                        }, 1500);
                      } else {
                        message.error({ 
                          key: loadingKey, 
                          content: '导入失败: ' + (commitResponse.data?.message || '未知错误') 
                        });
                        addImportLog('commit_failed', '导入失败', commitResponse.data);
                      }
                    } catch (timeoutError) {
                      message.destroy(loadingKey);
                      console.error('提交导入超时或失败:', timeoutError);
                      addImportLog('commit_timeout', '提交导入超时或失败', timeoutError);
                      message.error({ key: 'menu-import-timeout', content: '提交导入超时或失败，请稍后重试' });
                    }
                  } catch (commitError) {
                    console.error('提交导入失败:', commitError);
                    addImportLog('commit_error', '提交导入失败', commitError);
                    message.error({ key: 'menu-import-commit-error', content: '导入失败: ' + (commitError.response?.data?.message || commitError.message) });
                  }
                },
                okText: '确认导入',
                cancelText: '取消'
              });
            } catch (modalError) {
              console.error('显示确认对话框失败:', modalError);
              addImportLog('modal_error', '显示确认对话框失败', modalError);
              message.error({ key: 'menu-import-modal-error', content: '显示确认对话框失败，请重试' });
            }
          } else {
            // 校验失败或存在错误报告
            console.log('验证失败，状态:', job.status);
            addImportLog('validation_failed', '验证失败', { status: job.status, job });
            
            message.error('验证失败，请查看错误报告');
            
            try {
              const errorResponse = await menuAPI.downloadErrors(job_id);
              const url = window.URL.createObjectURL(new Blob([errorResponse.data]));
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `导入错误报告_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            } catch (errorDownloadError) {
              console.error('下载错误报告失败:', errorDownloadError);
              addImportLog('error_download_failed', '下载错误报告失败', errorDownloadError);
            }
          }
        } catch (validateError) {
          hide();
          console.error('验证过程出错:', validateError);
          addImportLog('validation_error', '验证过程出错', validateError);
          message.error('验证过程出错: ' + (validateError.response?.data?.message || validateError.message));
          return;
        }
      } catch (error) {
        console.error('导入失败:', error);
        addImportLog('error', '导入失败', error);
        message.error({ key: 'menu-import-error', content: '导入失败: ' + (error.response?.data?.message || error.message) });
      } finally {
        setImportLoading(false);
        cleanup();
      }
    });
  
    // 在下一个事件循环触发点击，提升兼容性（Safari等）
    setTimeout(() => input.click(), 0);
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      sorter: (a, b) => a.id - b.id
    },
    {
      title: '照片',
      dataIndex: 'image_url',
      key: 'image_url',
      width: 80,
      render: (imageUrl, record) => {
        if (imageUrl) {
          // 如果是相对路径，添加服务器基础地址
          const fullImageUrl = imageUrl.startsWith('/') ? `http://localhost:3001${imageUrl}` : imageUrl;
          return (
            <Image
              width={50}
              height={50}
              src={fullImageUrl}
              alt={record.name}
              style={{ objectFit: 'cover', borderRadius: '4px' }}
              fallback=""
            />
          );
        } else {
          return (
            <div style={{
              width: 50,
              height: 50,
              backgroundColor: '#f5f5f5',
              borderRadius: '4px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '12px',
              color: '#999'
            }}>
              无图片
            </div>
          );
        }
      }
    },
    {
      title: '菜品名称（中文）',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      ellipsis: true,
      render: (text, record) => (
        <Space>
          {record.isHot && <Tag color="red">热门</Tag>}
          {record.isNew && <Tag color="green">新品</Tag>}
          <Tooltip title={text}>
            <span>{text}</span>
          </Tooltip>
        </Space>
      )
    },
    {
      title: 'Name_English',
      dataIndex: 'name_en',
      key: 'name_en',
      width: 150,
      ellipsis: true,
      render: (text) => (
        <Tooltip title={text}>
          <span>{text || '-'}</span>
        </Tooltip>
      )
    },
    {
      title: 'Category 类别',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => {
        const categoryValue = category?.value || category;
        return (
          <Tag color={getCategoryColor(categoryValue)}>{String(categoryValue)}</Tag>
        );
      }
    },
    {
      title: 'Item Description 菜品描述',
      dataIndex: 'description',
      key: 'description',
      width: 200,
      ellipsis: true,
      render: (text, record) => {
        const desc = text || record.description_en;
        return (
          <Tooltip title={desc}>
            <span>{desc || '-'}</span>
          </Tooltip>
        );
      }
    },
    {
      title: 'Main Ingredients 主要原料',
      dataIndex: 'main_ingredients',
      key: 'main_ingredients',
      width: 180,
      ellipsis: true,
      render: (ingredients) => {
        if (!ingredients) return '-';
        const ingredientText = Array.isArray(ingredients) 
          ? ingredients.join(', ') 
          : String(ingredients);
        return (
          <Tooltip title={ingredientText}>
            <span>{ingredientText}</span>
          </Tooltip>
        );
      }
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 80,
      sorter: (a, b) => a.price - b.price,
      render: (price) => typeof price === 'number' ? `S$${price.toFixed(2)}` : 'S$0.00'
    },
    {
      title: '状态',
      dataIndex: 'is_available',
      key: 'is_available',
      width: 120,
      render: (available, record) => (
        <Select
          value={available ? 'available' : 'unavailable'}
          onChange={(value) => handleStatusChange(record.id, value)}
          style={{ width: '100%' }}
          size="small"
        >
          <Option value="available">
            <Tag color="green">可售</Tag>
          </Option>
          <Option value="unavailable">
            <Tag color="red">缺货</Tag>
          </Option>
          <Option value="hidden">
            <Tag color="orange">隐藏</Tag>
          </Option>
        </Select>
      )
    },
    {
      title: '菜品标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 150,
      render: (tags) => {
        if (!tags || !Array.isArray(tags)) return '-';
        const tagColors = {
          'recommended': 'gold',
          'spicy': 'red',
          'vegetarian': 'green',
          'healthy': 'blue',
          'signature': 'purple'
        };
        const tagLabels = {
          'recommended': '推荐',
          'spicy': '辣味',
          'vegetarian': '素食',
          'healthy': '健康',
          'signature': '招牌'
        };
        return (
          <Space size={[0, 4]} wrap>
            {tags.map(tag => (
              <Tag key={tag} color={tagColors[tag] || 'default'}>
                {tagLabels[tag] || tag}
              </Tag>
            ))}
          </Space>
        );
      }
    },
    {
      title: '菜品选项',
      dataIndex: 'options',
      key: 'options',
      width: 150,
      render: (options) => {
        if (!options || !Array.isArray(options)) return '-';
        const optionLabels = {
          'chicken': '鸡肉',
          'beef': '牛肉',
  
          'seafood': '海鲜',
          'vegetarian': '素食',
          'tofu': '豆腐'
        };
        return (
          <Space size={[0, 4]} wrap>
            {options.map(option => (
              <Tag key={option} color="cyan">
                {optionLabels[option] || option}
              </Tag>
            ))}
          </Space>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
        </Space>
      )
    }
  ];

  // 上传组件配置
  const uploadProps = {
    name: 'image',
    action: editingItem?.id ? `http://localhost:3001/api/admin/menu/items/${editingItem.id}/image` : null,
    maxCount: 1,
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('admin_token') || localStorage.getItem('token')}`,
    },
    accept: '.jpg,.jpeg,.png,.gif,.webp',
    beforeUpload: (file) => {
      // 检查文件类型
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif';
      if (!isImage) {
        message.error('只能上传 JPEG、PNG、WebP、GIF 格式的图片!');
        return false;
      }
      // 检查文件大小 (5MB)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB!');
        return false;
      }
      // 如果没有选择菜品，不允许上传
      if (!editingItem?.id) {
        message.error('请先保存菜品信息后再上传图片!');
        return false;
      }
      return true;
    },
    onChange(info) {
       if (info.file.status === 'uploading') {
         message.loading(`正在上传 ${info.file.name}...`, 0);
       } else if (info.file.status === 'done') {
         message.destroy();
         message.success(`${info.file.name} 上传成功!`);
         // 立即更新预览图片
         if (info.file.response?.data?.image_url) {
           const imageUrl = info.file.response.data.image_url;
           const fullImageUrl = imageUrl.startsWith('/') ? `http://localhost:3001${imageUrl}` : imageUrl;
           setPreviewImage(fullImageUrl);
         }
         // 刷新菜品列表以显示新图片
         fetchMenuItems();
       } else if (info.file.status === 'error') {
         message.destroy();
         message.error(`${info.file.name} 上传失败: ${info.file.response?.message || '未知错误'}`);
       }
     }
   };

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>菜单管理</Title>
      
      {/* 统计卡片 */}
      {isLoggedIn && (
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={6}>
            <Card>
              <Statistic 
                title="菜品总数" 
                value={stats.totalItems} 
                prefix={<ShoppingOutlined />} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="可售菜品" 
                value={stats.availableItems} 
                prefix={<DollarOutlined />} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="热门菜品" 
                value={stats.hotItems} 
                prefix={<FireOutlined />} 
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic 
                title="总销量" 
                value={stats.totalSales} 
                prefix={<StarOutlined />} 
              />
            </Card>
          </Col>
        </Row>
      )}
      
      {/* 登录表单 */}
      {!isLoggedIn ? (
        <Card title="管理员登录">
          <div>
            <div style={{ marginBottom: '16px' }}>
              <label>邮箱：</label>
              <Input 
                value={loginForm.email} 
                onChange={(e) => setLoginForm({...loginForm, email: e.target.value})}
              />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <label>密码：</label>
              <Input.Password 
                value={loginForm.password} 
                onChange={(e) => setLoginForm({...loginForm, password: e.target.value})}
              />
            </div>
            <Button 
              type="primary" 
              onClick={handleLogin} 
              loading={loginLoading}
            >
              登录
            </Button>
          </div>
        </Card>
      ) : (
        <Card style={{ marginBottom: '24px' }}>
          <Space>
            <span>已登录</span>
            <Button onClick={handleLogout}>退出登录</Button>
          </Space>
        </Card>
      )}
      
      {/* 菜品列表 */}
      {isLoggedIn && (
        <Card title="菜品列表">
          {/* 操作按钮 */}
          <div style={{ marginBottom: '16px' }}>
            <Space>
              <Button 
                icon={<DownloadOutlined />} 
                onClick={handleDownloadTemplate} 
                loading={templateLoading}
              >
                下载模板
              </Button>
              <Button 
                icon={<ImportOutlined />} 
                onClick={handleImport} 
                loading={importLoading}
              >
                导入
              </Button>
              <Button 
                icon={<ExportOutlined />} 
                onClick={handleExport} 
                loading={exportLoading}
              >
                导出
              </Button>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={() => window.location.reload()}
              >
                刷新
              </Button>
              {isImportDebugEnabled() && (
                <Button onClick={exportImportLogs}>导出日志</Button>
              )}
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={() => {
                  setEditingItem(null);
                  form.resetFields();
                  setModalVisible(true);
                }}
              >
                添加菜品
              </Button>
            </Space>
          </div>
          
          {/* 过滤器 */}
          <div style={{ marginBottom: '16px' }}>
            <Space>
              <Input 
                placeholder="搜索菜品名称或描述" 
                value={searchText} 
                onChange={(e) => setSearchText(e.target.value)} 
                prefix={<SearchOutlined />} 
                style={{ width: '250px' }}
              />
              <Select 
                value={categoryFilter} 
                onChange={setCategoryFilter} 
                style={{ width: '120px' }}
              >
                <Option value="all">全部分类</Option>
                {categories.map(cat => (
                  <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                ))}
              </Select>
              <Select 
                value={statusFilter} 
                onChange={setStatusFilter} 
                style={{ width: '120px' }}
              >
                <Option value="all">全部状态</Option>
                <Option value="available">可售</Option>
                <Option value="unavailable">缺货</Option>
                <Option value="hidden">隐藏</Option>
              </Select>
              <RangePicker 
                value={dateRange} 
                onChange={setDateRange} 
              />
            </Space>
          </div>
          
          {/* 表格 */}
          <div>
            {loading ? (
              <div>加载中...</div>
            ) : (
              <BaseTable 
                dataSource={filteredData} 
                columns={columns} 
                rowKey="id" 
                scroll={{ x: 1500, y: 600 }}
                pagination={{
                  current: currentPage,
                  pageSize: pageSize,
                  onChange: (page) => setCurrentPage(page),
                  onShowSizeChange: (_, size) => setPageSize(size),
                  showSizeChanger: true,
                  showTotal: (total) => `共 ${total} 条记录`
                }}
                rowSelection={{
                  selectedRowKeys,
                  onChange: setSelectedRowKeys
                }}
              />
            )}
          </div>
        </Card>
      )}
      
      {/* 编辑/添加菜品对话框 */}
      <Modal 
        title={editingItem ? '编辑菜品' : '添加菜品'} 
        visible={modalVisible} 
        onCancel={() => setModalVisible(false)}
        width={800}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>取消</Button>,
          <Button key="submit" type="primary" onClick={() => form.submit()}>保存</Button>
        ]}
      >
        <Form 
          form={form} 
          layout="vertical"
          onFinish={async (values) => {
            try {
              if (editingItem) {
                // 编辑现有菜品 - 调用API更新
                const response = await menuAPI.updateMenuItem(editingItem.id, values);
                if (response.data && response.data.success) {
                  message.success('菜品更新成功');
                  await fetchMenuItems(); // 重新获取数据
                } else {
                  message.error('菜品更新失败');
                }
              } else {
                // 添加新菜品 - 调用API创建
                const response = await menuAPI.createMenuItem(values);
                if (response.data && response.data.success) {
                  message.success('菜品添加成功');
                  await fetchMenuItems(); // 重新获取数据
                } else {
                  message.error('菜品添加失败');
                }
              }
              setModalVisible(false);
              form.resetFields();
            } catch (error) {
              console.error('保存菜品失败:', error);
              message.error('保存菜品失败');
            }
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="name" 
                label="菜品名称（中文）" 
                rules={[{ required: true, message: '请输入菜品名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item 
                name="name_en" 
                label="菜品名称（英文）" 
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="category" 
                label="分类" 
                rules={[{ required: true, message: '请选择分类' }]}
              >
                <Select placeholder="请选择分类">
                  {categories.map(cat => (
                    <Option key={cat.value} value={cat.value}>{cat.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>

          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="price" 
                label="价格" 
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <InputNumber 
                  min={0} 
                  precision={2} 
                  style={{ width: '100%' }} 
                  formatter={value => `S$ ${value}`}
                  parser={value => value.replace(/S\$\s?/g, '')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item 
                name="originalPrice" 
                label="原价" 
              >
                <InputNumber 
                  min={0} 
                  precision={2} 
                  style={{ width: '100%' }} 
                  formatter={value => `S$ ${value}`}
                  parser={value => value.replace(/S\$\s?/g, '')}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="stock" 
                label="库存" 
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>

          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item 
                name="description" 
                label="描述（中文）" 
              >
                <TextArea rows={3} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item 
                name="description_en" 
                label="描述（英文）" 
              >
                <TextArea rows={3} />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item 
                name="main_ingredients" 
                label="主要配料" 
              >
                <TextArea rows={2} placeholder="请输入主要配料，用逗号分隔" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item 
                name="isHot" 
                valuePropName="checked" 
                label="热门" 
              >
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item 
                name="isNew" 
                valuePropName="checked" 
                label="新品" 
              >
                <Switch />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item 
                label="图片" 
              >
                <Upload {...uploadProps} listType="picture-card">
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传</div>
                  </div>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
          
          {/* 菜品标签设置 */}
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item 
                name="tags" 
                label="菜品标签" 
              >
                <Select 
                  mode="multiple" 
                  placeholder="选择菜品标签"
                  style={{ width: '100%' }}
                >
                  <Option value="recommended">推荐</Option>
                  <Option value="spicy">辣味</Option>
                  <Option value="vegetarian">素食</Option>
                  <Option value="healthy">健康</Option>
                  <Option value="signature">招牌</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          {/* 菜品选项设置 */}
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item 
                name="options" 
                label="菜品选项" 
              >
                <Select 
                  mode="multiple" 
                  placeholder="选择可选配菜/肉类"
                  style={{ width: '100%' }}
                >
                  <Option value="chicken">鸡肉</Option>
                  <Option value="beef">牛肉</Option>
  
                  <Option value="seafood">海鲜</Option>
                  <Option value="vegetarian">素食</Option>
                  <Option value="tofu">豆腐</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
      
      {/* 图片预览 */}
      <Modal 
        visible={previewVisible} 
        footer={null} 
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="预览" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default ImprovedMenuPage;